// survey.js
// const app = getApp()
const { envList } = require('../../envList.js');
const db = wx.cloud.database()
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
import { areaSingleList, indexSurveyOption } from '../index/staff'
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';


Page({
  data: {
    showUploadTip: false,
    user_radios:{},
    user_radio1:'1',
    user_radio2:'1',
    indexRadio: [],
    testRadio:[],
    envList,
    selectedEnv: envList[0],
    haveCreateCollection: false,
    userInfo: {},
    isFirstLogin: 0,
    selectedEnv: envList[0],
    open_id: '',
    isLogin: false,
    haveSub: false,
    digShow: false ,// 对话框地域选择
    areaRadio: '总部中区',
    icon: { // 区域选择logo变换
      normal: 'https://imgg.cookcloud.club/%E6%96%B0%E4%BC%9ABK.png',
      active: 'https://imgg.cookcloud.club/%E6%96%B0%E4%BC%9AAC.png',
      jiangmenNormal: 'https://imgg.cookcloud.club/%E6%B1%9F%E9%97%A8bk.png',
      jiangmenActive:'https://imgg.cookcloud.club/%E6%B1%9F%E9%97%A8ac.png',
      heshanNom: 'https://imgg.cookcloud.club/%E9%B9%A4%E5%B1%B1bk.png',
      heshanAc: 'https://imgg.cookcloud.club/%E9%B9%A4%E5%B1%B1ac.png',
      kaipingNom: 'https://imgg.cookcloud.club/%E5%BC%80%E5%B9%B3bk.png',
      kaipingAc: 'https://imgg.cookcloud.club/%E5%BC%80%E5%B9%B3AC.png'
    },
    curArea: '总部中区', // 当前区域
    allArea: areaSingleList,
    withWorer: false, //扫码进来员工模式数据
    showLogin: false, // 是否显示微信授权按钮
    startScreen: false, //开屏海报
    indexSurveyOption: indexSurveyOption,
    secondPage: true, // 作为第二页跳转后的模式，当前采用
    boxResult:[], // 多选框 // 问卷提交项目
    othersOpValue: [], // 复选框手动输入项1 问卷提交项目
  },

  async onReady() {    
    // this.getUserInfo()// wx.clearStorageSync()
    console.log('look area', this.data.allArea)
  },
  onLoad: function (options) {
     wx.redirectTo({
        // url: `/pages/luckyDraw/index`,
        // url: `/pages/haibao/haibao`,
        // url: `/pages/workerRace/index?option=default&area=总部中区&worker=周纪峰&uuid=zhoujifeng-总部中-装维工程师`,
        // url: `/pages/workerRace/index?option=default&area=总部中区`
      });
      //获取二维码中的员工ID（如果有的话）worker  uuid
      let worker_name = options['worker']
      let id_num = options['uuid']
      let status = options['status']
      console.log('MyID', id_num, worker_name)
      // wx.setStorageSync('workerId', 'id_number' ) // 临时测试开启.
      // wx.setStorageSync('workerName', 'worker_name')
      // this.setData({ withWorer: true})
      if(status=='second'){
        this.setData({ secondPage: true })
      }else{
        if(id_num && id_num.length > 0 && worker_name ){
          console.log('MyID>0')
          wx.setStorageSync('workerId', id_num )
          wx.setStorageSync('workerName', worker_name)
          this.setData({ withWorer: true})
      }     
      setTimeout(()=>{
        this.setData({ startScreen: false })
      },5000)
      }
      const accountInfo = wx.getAccountInfoSync();
      console.log('小程序',accountInfo.miniProgram) // 小程序 appId
      
  },
  /**
* 用户点击右上角分享
*/
onShareAppMessage: function(res) {
  if (res.from === 'button') {
    // 来自页面内转发按钮
    return {
        title: "江门广电网络优质服务评选",
        path: 'pages/index/index?option=default&area=总部中区'
      }
  }
    return {
      title: "江门广电网络优质服务评选",
      path: 'pages/index/index?option=default&area=总部中区'
    }
  },
  //用户点击右上角分享朋友圈
	onShareTimeline: function () {
		return {
	      title: '这个小程序真好，分享到朋友圈',
	      query: {
	        key: 'value'
	      },
	    }
	},
  // 微信授权获取信息第一步，首次登入显示（数据库用户信息判断）
  async getLoginInfo(){
    let data = await this.getUserInfo()
    // data.then(resp=>{ console.log('Promise测试',resp) })
    console.log('index页登陆了吗', data)
    // if(data==false || this.data.isFirstLogin>0 || !data){
    //   console.log('index页首次登录，准备获取个人信息')
    //   wx.getUserProfile({
    //     desc: '用于完善活动资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
    //     success: (res) => {
    //       console.log('index页getUserProfile RES',res.userInfo)
    //       this.setData({
    //         userInfo: res.userInfo,               
    //       })
    //       db.collection('users').add({
    //       data: {
    //         wechat_name: res.userInfo.nickName,
    //         avatarUrl: res.userInfo.avatarUrl,
    //         curtime: new Date().toLocaleString(),
    //         timestamp: new Date().getTime(),
    //         user_type: 'wechat_user',
    //         have_sub: false,
    //         sub_num: 10,
    //         luckyChance: 3 // 抽奖机会
    //       }  })
    //       this.setData({isLogin: true, digShow: true },()=>{
    //         wx.redirectTo({
    //           // url: `/pages/workerRace/index?option=${tranData}&area=${this.data.areaRadio}&worker=小张&uuid=1001`,
    //           url: `/pages/luckyDraw/index`,
    //           // url: `/pages/haibao/haibao`,
    //         });               
    //       })
    //     },
    //     fail: (res)=>{ 
    //       wx.showToast({
    //         title: '请重新登录',
    //       })
    //       console.log('微信获取用户出错|或被拒绝',res) }
    //   }) } else{
    //     wx.redirectTo({
    //       // url: `/pages/workerRace/index?option=${tranData}&area=${this.data.areaRadio}&worker=小张&uuid=1001`,
    //       url: `/pages/luckyDraw/index`,
    //       // url: `/pages/haibao/haibao`,
    //     });               
    //   }
    
  },
  // 数据库搜索用户信息(openid)判断是否存在该用户，三种情况，决定跳转到哪里
   async getUserInfo(e){
     console.log('User Info Method', e)
      wx.cloud.callFunction({
        name: 'quickstartFunctions',    
        data: { type: 'getOpenId'},  config: { env: this.data.selectedEnv.envId },
      }).then((resp) => {
        this.setData({ open_id: resp.result.openid }) // console.log('OPID',e.detail.userInfo) 
        db.collection('users').where({
          _openid: this.data.open_id
        }).get().then( res => {
          console.log('UserGetCheck', res)
          if(res.data == ""){
            console.log("准备授权数据库登记-是否提交过问卷？",this.data.haveSub)  // 第一次登录，准备调用微信API
            this.setData({isFirstLogin: 1, showLogin: true})     // 开始显示授权按钮
            return false  
          }else{
            console.log("已经登录过不用授权") 
            if( res.data[0].sub_num < 1 ){
                this.setData({haveSub: true, isLogin: true})
                // wx.redirectTo({
                //   url: '/pages/luckyDraw/index',  // 正式上线需改为 luckyDraw, ranking, workerRace
                //   // url: '/pages/ranking/index?worker=嘉兴',  // 正式上线需改为luckyDraw, ranking
                // // })           
                Toast.fail({
                  message: '本月投票超额，感谢参与！',
                  forbidClick: true,
                });              
                return true  } else{  // 正常还没投的继续模式
                this.setData({
                  userInfo: {nickName: res.data[0].wechat_name },   
                  isLogin: true,
                  digShow: false         
                })
                let tranData = JSON.stringify(this.data.user_radios)
                // 待插入数据库问卷数据todo
                db.collection('sales').add({
                  data: {
                    surveyData: this.data.boxResult,  // 多选框问卷信息
                    otherOption: this.data.othersOpValue,  // 用户手动输入的其他信息
                    subTime: new Date().toLocaleString(),
                    timestamp: new Date().getTime(),
                  }
                }).then((res)=>{
                  console.log('----插入数据库问卷数据', res)    
                  wx.redirectTo({
                      url: '/pages/luckyDraw/index',  // 正式上线需改为 luckyDraw, ranking, workerRace
                      // url: '/pages/ranking/index?worker=嘉兴',  // 正式上线需改为luckyDraw, ranking
                    })                 
                })  
                return true
               
              //   wx.switchTab({
              //     url: '/pages/index/index',//登录成功后要跳转的页面
              //  })
              }
                 
          }
        } ) 
      wx.hideLoading();
      }).catch((e) => {
      console.log('云函数index-idbug', e)   
      //  wx.hideLoading();
      });

    
    // wx.cloud.callFunction({
    //   name: 'quickstartFunctions',    
    //   data: { type: 'getOpenId'},  config: { env: this.data.selectedEnv.envId },
    // }).then((resp) => {
    //   // console.log('OPID', resp.result.openid, e.detail.userInfo)  
    //   const openid = resp.result.openid
    //  wx.hideLoading();
    // }).catch((e) => {
    //  console.log('idbug', e)   
    //  wx.hideLoading();
    // });
  },
  runAsync1(jj){
    var p = new Promise(function (resolve, reject) {
      //做一些异步操作
      setTimeout(function () {
        console.log(jj);
        resolve("runAsync1测试的数据1");
      }, 0);
    });
    return p;
  },
  onRadio1Change(event) {
    let index = event.currentTarget.dataset.index;
    console.log('选项', index)
    let trandata = this.data.user_radios
    trandata[`radio${ index }`] = event.detail
    this.setData({
      user_radios: trandata,
    });
  },
  onCheckBoxChange(event){
    let index = event.currentTarget.dataset.index;
    let trandata = this.data.boxResult
    trandata[index] = event.detail
    console.log('onCheckBoxChange', index, trandata)
    this.setData({
      boxResult: trandata,
    });
  },
  // onRadio2Change(event) {
  //   let trandata = this.data.user_radios
  //   trandata.radio2 = event.detail
  //   this.setData({
  //     user_radios: trandata,
  //   });
  // },


  onChangeShowEnvChoose() {
    wx.showActionSheet({
      itemList: this.data.envList.map(i => i.alias),
      success: (res) => {
        console.log(res.tapIndex);
        this.onChangeSelectedEnv(res.tapIndex);
      },
      fail (res) {
        console.log(res.errMsg);
      }
    });
  },



  jumpPage(e) {
    wx.navigateTo({
      url: '/pages/index/index',
    });
  },
  onClickDatabase(powerList) { //模板示范函数
    wx.cloud.callFunction({
      name: 'quickstartFunctions',
      config: {
        env: this.data.selectedEnv.envId
      },
      data: {
        type: 'createCollection'
      }
    }).then((resp) => {}).catch((e) => {
    });
  },

  checkIsSub(){
    
  }
 ,
  async testFunc(e) {
    console.log('问卷数据', Object.keys(this.data.indexSurveyOption).length, Object.keys(this.data.boxResult).length,this.data.boxResult )
    let haveContent = Object.keys(this.data.boxResult).length >= Object.keys(this.data.indexSurveyOption).length
    if(!haveContent){
      wx.showToast({
        title: '请填写问卷',
        icon: 'none'
      });
      return
    }
    let tranData = JSON.stringify(this.data.user_radios)
    if(this.data.withWorer){
       wx.redirectTo({
          url: `/pages/${e.currentTarget.dataset.page}/index?option=${tranData}&area=总部中区`,
        });
    }else{
      await this.getLoginInfo()     
    }
    // Dialog.alert({
    //   title: '标题',
    //   message: '弹窗内容',
    // }).then(() => {
    //   // on close
    // });
    // wx.redirectTo({
    //   url: `/pages/${e.currentTarget.dataset.page}/index?option=${tranData}&area=总部中区`,
    // });
    // wx.showToast({
    //   title: '登录中..',
    //   icon: 'none'
    // });
    // db.collection('users').add({
    //   // data 字段表示需新增的 JSON 数据
    //   data: {
    //     user_type: "learn cloud database",
    //     wechat_name: 'looklook',
    //     user_id: 3,
    //     race_target: 'foofoo',
    //     race_source: 8,
    //     curtime: new Date("2021-09-01"),
    //   }
    // })
    // .then(res => {
    //   console.log(res)
    //  
    // })
  },
  onDigClose(){
    this.setData({ digShow: false })
  },
  onAreaChange( event ){
    console.log('area', event.detail, this.data.digShow)
    this.setData({
      areaRadio: event.detail,
    });
  },
  onDigConfirm(event){ // 选择区域后跳转到第二页
    console.log('confirmArea', this.data.areaRadio)
    let tranData = JSON.stringify(this.data.user_radios)
     wx.redirectTo({
      url: `/pages/workerRace/index?option=${tranData}&area=${this.data.areaRadio}&worker=小张&uuid=1001`,
      // url: `/pages/index/index?option=${tranData}&area=${this.data.areaRadio}`,
      // url: `/pages/haibao/haibao`,
    });
  },
  onStartScreenClose(){
    this.setData({ startScreen: false })
  },
  othersOpValueChange(event){
    let index = event.currentTarget.dataset.index;
    console.log('吃饭', event.detail, index)
    let oldData = this.data.othersOpValue
    oldData[index] = event.detail
    this.setData({
      othersOpValue:oldData
    },()=>{
      console.log('othersOpValue', this.data.othersOpValue)
    })
  }
});

    //首先查看是否得到用户 的授权
    // wx.getSetting({
    //   success:(res)=>{
    //     //console.log(res)
    //     //res.authSetting['scope.userInfo']   代表用户授予权限的状态
    //     console.log('授权状态',res.authSetting['scope.userInfo'])
    //     if(res.authSetting['scope.userInfo']){
    //       //如果用户给与了这个权限 可以进行获取用户信息
    //       wx.getUserInfo({
    //         success: (res) => {
    //           console.log(res.userInfo)
    //           that.setData({
    //             userInfo: res.userInfo
    //           })   } })
    //     }else{
    //       //如果用户没有给与这个权限则  发送询问权限的请求
    //       wx.authorize({
    //         scope:"scope.userInfo",
    //         success:(res)=>{
    //           console.log(res)
    //         }   })  }   }  })
